import key from 'keymaster';

const pointData = localStorage.getItem('userData') || '[]';
const pageData = localStorage.getItem('pageData') || '{}';
function overSave(name, data) {
  localStorage.setItem(name, JSON.stringify(data));
}

export default {
  namespace: 'editorModel',
  state: {
    pageData:
      {
        width: 512, // 实际页面宽度
        height: 768, // 实际页面高度
        bgImg: 'https://fakeimg.pl/512x768/FFF/EEE/',
        scale: 1, // 编辑器宽高/实际页面宽高
      } || JSON.parse(pageData),
    pointData: JSON.parse(pointData),
    curPoint: null,
  },
  // 接收 action，同步更新 state
  reducers: {
    addPointData(state, { payload }) {
      let pointData = [...state.pointData, payload];
      overSave('userData', pointData);
      return {
        ...state,
        pointData,
        curPoint: payload,
      };
    },
    modPointData(state, { payload }) {
      const { id } = payload;
      const pointData = state.pointData.map((item) => {
        if (item.id === id) {
          return payload;
        }
        return { ...item };
      });
      overSave('userData', pointData);
      return {
        ...state,
        pointData,
        curPoint: payload,
      };
    },
    clearAll(state) {
      overSave('userData', []);
      return {
        ...state,
        pointData: [],
        curPoint: null,
      };
    },
    delPointData(state, { payload }) {
      const { id } = payload;
      const pointData = state.pointData.filter((item) => item.id !== id);
      overSave('userData', pointData);
      return {
        ...state,
        pointData,
        curPoint: null,
      };
    },
    modPageData(state, { payload }) {
      const pageData = {
        ...state.pageData,
        ...payload,
      };
      overSave('pageData', pageData);
      return {
        ...state,
        pageData,
      };
    },
  },
  // 处理异步操作和业务逻辑，不直接修改 state
  effects: {},
  // 用于订阅一个数据源，然后根据需要 dispatch 相应的 action
  subscriptions: {
    keyEvent({ dispatch, state }) {
      // 删除
      key('delete, backspace', () => {
        dispatch({
          type: 'editorModel/keyboardDelPointData',
        });
      });
    },
  },
};
